
/**
 * 下载文件
 * @param {*} fileName 
 * @param {*} content 
 */
function downloadFile (fileName, content) {
    var aLink = document.createElement('a')
    // new Blob([content]);
    var blob = base64ToBlob(content) 
    var evt = document.createEvent('HTMLEvents')
    // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    evt.initEvent('click', true, true) 
    aLink.download = fileName
    aLink.href = URL.createObjectURL(blob)
    // 兼容火狐
    aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })) 
}

/**
 * base64转图片
 * @param {*} code 
 */
function base64ToBlob (code) {
    var parts = code.split(';base64,')
    var contentType = parts[0].split(':')[1]
    var raw = window.atob(parts[1])
    var rawLength = raw.length
    var uInt8Array = new Uint8Array(rawLength)
    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
    }
    return new Blob([uInt8Array], { type: contentType })
}

export { downloadFile }
